package Socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

//可以在网页输入  http://127.0.0.1:8080/（文件地址（html文件的），让服务器打开）
public class ServerSocket2 {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8080);
        while(true)
        {
            try{
                Socket socket = server.accept();
                InputStream is = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int len=0;
        /*while((len=is.read(bytes))!=-1)
        {
            System.out.println(new String(bytes,0,len));
        }*/

                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                //把is转化为字符缓冲输出流
                //把客户端请求信息的地址读取出来，在回复的第一行
                String line = br.readLine();
                //切割一下，获取文件的路径
                String[] arr = line.split(" ");
                String htmlpath = arr[1].substring(1);

                FileInputStream fis = new FileInputStream(htmlpath);
                //用fis读取路径文件
                OutputStream os = socket.getOutputStream();

                //一些以后学HTML的
                os.write("HTTP/1.1 200 OK\r\n".getBytes());
                os.write("Content-Type:text/html\r\n".getBytes());
                //要写空行
                os.write("\r\n".getBytes());

                while((len = fis.read(bytes))!=-1)
                {
                    os.write(bytes,0,len);
                }

                fis.close();
                socket.close();
            }catch (IOException E)
            {
                System.out.println(E);
            }
        }
        //server.close();
    }
}
